package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 地区资源控制器
 */
@Controller
@RequestMapping("region")
public class RegionController {
    @Autowired
    private IRegionService regionService;

    @RequestMapping("list")
    public String list(){
        return "region/list";
    }

    @RequestMapping("selectByParentId")
    @ResponseBody
    public List selectByParentId(Long parentId, String type){
        List<Region> regions = regionService.selectForList(parentId);
        if ("tree".equals(type)){
            List<Map<String,Object>> list = new ArrayList<>();
            for (Region region : regions) {
                list.add(region.toTreeMap());
            }
            return list;
        }else {
            return regions;
        }
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Region region){
        JsonResult jsonResult = new JsonResult();
        try {
            regionService.saveOrUpdate(region);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.mark("操作失败!");
        }
        return jsonResult;
    }
    @RequestMapping("changeState")
    @ResponseBody
    public JsonResult changeState(Long id, Integer state){
        JsonResult jsonResult = new JsonResult();
        try {
            regionService.changeState(id, state);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.mark("操作失败!");
        }
        return jsonResult;
    }

}
